package simplyrugby.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import simplyrugby.common.LoginContext;
import simplyrugby.common.Result;
import simplyrugby.entity.User;
import simplyrugby.service.UserService;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    @PostMapping(path = {"/register", "/add"})
    public Result register(@RequestBody User user) {
        if (userService.exist(user.getUsername())) {
            return Result.fail().message("Username exist.");
        }
        boolean save = userService.save(user);
        return Result.success().data(save);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String token = userService.login(user);
        return Result.success().data(token);
    }

    @GetMapping("/exist")
    public Result exist(@RequestParam String username) {
        boolean isExist = userService.exist(username);
        return Result.success().data(isExist);
    }

    @GetMapping(path = {"/get", "/info"})
    public Result get(@RequestParam(required = false) String id) {
        if (id == null) {
            id = LoginContext.getLoginUserId();
        }
        User user = userService.details(id);
        return Result.success().data(user);
    }


    @PostMapping("/update")
    public Result updateById(@RequestBody User user) {
        boolean flag = userService.updateById(user);
        return flag ? Result.success() : Result.fail().message("修改用户信息失败");
    }

    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable String id) {
        boolean b = userService.removeById(id);
        return Result.success().data(b);
    }


    @PostMapping("/list")
    public Result list(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize,
                       @RequestBody User user
    ) {
        Page<User> page = userService.list(user, pageNum, pageSize);
        return Result.success().data(page);
    }
}

